package com.kgc.controller;



import com.alibaba.fastjson.JSON;
import com.kgc.config.WechatConfig;
import com.kgc.dto.UsersDto;
import com.kgc.service.UsersService;
import com.kgc.utils.UrlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author zsy
 * @since 2021-08-04
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UsersController {

    @Autowired
    private UsersService usersService;
    @Autowired
    private WechatConfig wechatConfig;

    @GetMapping("/login/wechat")
    public void loginWeChat(HttpServletResponse response){
        //设置登录地址
        String url = wechatConfig.getOpen_url() +
                "?appid=" + wechatConfig.getAppid() +
                "&redirect_uri=" + wechatConfig.getRedirect_uri() +
                "&response_type=" + wechatConfig.getCode() +
                "&scope=" + wechatConfig.getScope() +
                "&state=" + wechatConfig.getState();
        try {
            //第一次访问微信
            response.sendRedirect(url);
        } catch (IOException e) {
            log.error("发送请求异常");
        }
    }
    @GetMapping("/wechat/callback")
    public void callback(String code,HttpServletResponse response) throws IOException {
        //第一次访问给的数据 code 用于获取token和用户信息
        log.info("微信给的code:",code);
        //第二次访问路径
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + wechatConfig.getAppid() +
                "&secret=" + wechatConfig.getSecret() +
                "&code=" + code +
                "&grant_type=authorization_code";
        //接受第第二次访问结果
        String resultJosn = UrlUtils.loadURL(url);
        Map<String, Object> map = JSON.parseObject(resultJosn,Map.class);
        String access_token = map.get("access_token").toString();
        String openid = map.get("openid").toString();
        log.info("第二次访问给的数据"+resultJosn);

        UsersDto usersDto = usersService.loginweChat(access_token,openid);
        //颁发token
        String name = usersDto.getUserName();
        String token = usersDto.getToken();
        //跳转首页
       // response.sendRedirect(wechatConfig.getSuccess_url()+"?token="+token+"&userinfo="+ URLEncoder.encode(name,"UTF-8"));

         // 4.跳转到首页
        try {
            response.sendRedirect(wechatConfig.getSuccess_url() + "?token=" + token + "&userInfo=" + URLEncoder.encode(name, "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


